﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;
using System.Runtime.InteropServices;
using System.Web;
using System.Net;
using System.Diagnostics;
namespace Bingrounder
{
    public partial class SettingsForm : Form
    {
        private bool _bingrounderStopped = false;

        public SettingsForm()
        {
            InitializeComponent();

            Styles.Items.Add(Wallpaper.Style.Centered);
            Styles.Items.Add(Wallpaper.Style.Stretched);
            Styles.Items.Add(Wallpaper.Style.Tiled);
        }

        private void Systray_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            loadSettings();
            Show();
            if (this.WindowState == FormWindowState.Minimized)
                this.WindowState = FormWindowState.Normal;

            this.Activate();
            Cursor = Cursors.Default;
        }

        private void BingPoller_Tick(object sender, EventArgs e)
        {
            CheckBingAndGetImage();
        }

        public void CheckBingAndGetImage()
        {
            try
            {
                Uri bingUrl = GetBingImageUrl();
                RegistryHelper helper = new RegistryHelper("Bingrounder");
                if (helper["CurrentBingImage"].ToString() != bingUrl.LocalPath)
                {
                    helper["CurrentBingImage"] = bingUrl.LocalPath;

                    Wallpaper.Set(bingUrl, (Wallpaper.Style)int.Parse(helper["Style"].ToString()));
                }
            }
            catch (WebException ex)
            {
                Systray.ShowBalloonTip(10000, "Could Not Connect", "Could not connect to Bing. Please check your internet connection.", ToolTipIcon.Error);
            }
        }

        private Uri GetBingImageUrl()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.bing.com");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader reader = new StreamReader(response.GetResponseStream());
            string bingResponse = reader.ReadToEnd();

            Uri imageUrl = new Uri("http://www.bing.com" + bingResponse.Substring(bingResponse.IndexOf("g_img={url:") + 12).Replace("\\", "").Substring(0, bingResponse.Substring(bingResponse.IndexOf("g_img={url:") + 12).Replace("\\", "").IndexOf(".jpg") + 4));

            request = null;
            response = null;
            reader.Close();
            reader.Dispose();

            return imageUrl;
        }

        private void SaveLocally_CheckedChanged(object sender, EventArgs e)
        {
            if (SaveLocally.Checked)
            {
                if (SaveBingFolderDialog.ShowDialog(this) == DialogResult.OK)
                {
                    SaveBingFolder.Text = SaveBingFolderDialog.SelectedPath;
                }
            }
            SaveBingFolder.Visible = SaveLocally.Checked;
            FolderBrowse.Visible = SaveLocally.Checked;
        }

        private void pauseBingrounderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_bingrounderStopped)
            {
                pauseBingrounderToolStripMenuItem.Text = "Pause &Bingrounder";
                _bingrounderStopped = false;
                BingPoller.Start();
                CheckBingAndGetImage();
            }
            else
            {
                pauseBingrounderToolStripMenuItem.Text = "Start &Bingrounder";
                _bingrounderStopped = true;
                BingPoller.Stop();
            }
        }

        private void SettingsForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to exit Bingrounder?", "Are You Sure?", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel)
                e.Cancel = true;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void editPreferencesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            loadSettings();
            Show();
            WindowState = FormWindowState.Normal;
            this.Activate();
        }

        private void SettingsForm_Resize(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
                Hide();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                RegistryHelper helper = new RegistryHelper("Bingrounder");
                helper["Style"] = ((int)(Wallpaper.Style)Styles.SelectedItem).ToString();
                helper["RunAtStartup"] = RunStartup.Checked.ToString();
                helper["SaveLocally"] = SaveLocally.Checked.ToString();

                if (SaveLocally.Checked)
                    helper["BingImagePath"] = SaveBingFolder.Text;
                else
                    helper["BingImagePath"] = string.Empty;

                if (RunStartup.Checked)
                {
                    RegistryKey startupKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                    startupKey.SetValue("Bingrounder", Application.ExecutablePath);
                }
                else
                {
                    RegistryKey startupKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                    startupKey.DeleteValue("Bingrounder");
                }
                Uri bingUrl = GetBingImageUrl();
                Wallpaper.Set(bingUrl, (Wallpaper.Style)int.Parse(helper["Style"].ToString()));
                Hide();
            }
            catch (WebException ex)
            {
                Systray.ShowBalloonTip(10000, "Could Not Connect", "Could not connect to Bing. Please check your internet connection.", ToolTipIcon.Error);
                Hide();
            }
            Cursor = Cursors.Default;
        }

        private void loadSettings()
        {
            Cursor.Current = Cursors.WaitCursor;
            RegistryHelper helper = new RegistryHelper("Bingrounder");

            for (int i = 0; i < Styles.Items.Count; i++)
            {
                if (((int)(Wallpaper.Style)Styles.Items[i]).ToString() == helper["Style"].ToString())
                {
                    Styles.SelectedIndex = i;
                    break;
                }
            }
            RunStartup.Checked = bool.Parse(helper["RunAtStartup"].ToString());
            SaveLocally.Checked = bool.Parse(helper["SaveLocally"].ToString());

            if (SaveLocally.Checked)
            {
                FolderBrowse.Visible = true;
                SaveBingFolder.Visible = true;
                SaveBingFolder.Text = helper["BingImagePath"].ToString();
            }
            Cursor.Current = Cursors.Default;
        }

        private void FolderBrowse_Click(object sender, EventArgs e)
        {
            if (SaveBingFolderDialog.ShowDialog(this) == DialogResult.OK)
            {
                SaveBingFolder.Text = SaveBingFolderDialog.SelectedPath;
            }
            
        }

        private void goToBingcomToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://www.bing.com");
        }
    }

    public sealed class Wallpaper
    {
        Wallpaper() { }

        const int SPI_SETDESKWALLPAPER = 20;
        const int SPIF_UPDATEINIFILE = 0x01;
        const int SPIF_SENDWININICHANGE = 0x02;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

        public enum Style : int
        {
            Tiled,
            Centered,
            Stretched
        }

        public static void Set(Uri uri, Style style)
        {
            System.IO.Stream s = new WebClient().OpenRead(uri.ToString());

            System.Drawing.Image img = System.Drawing.Image.FromStream(s);
            string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
            img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp);
            RegistryHelper helper = new RegistryHelper("Bingrounder");
            if (bool.Parse(helper["SaveLocally"].ToString()))
            {
                FileInfo info = new FileInfo(uri.LocalPath);
                string savePath = Path.Combine(helper["BingImagePath"].ToString(), info.Name);
                img.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
            if (style == Style.Stretched)
            {
                key.SetValue(@"WallpaperStyle", 2.ToString());
                key.SetValue(@"TileWallpaper", 0.ToString());
            }

            if (style == Style.Centered)
            {
                key.SetValue(@"WallpaperStyle", 1.ToString());
                key.SetValue(@"TileWallpaper", 0.ToString());
            }

            if (style == Style.Tiled)
            {
                key.SetValue(@"WallpaperStyle", 1.ToString());
                key.SetValue(@"TileWallpaper", 1.ToString());
            }

            SystemParametersInfo(SPI_SETDESKWALLPAPER,
                0,
                tempPath,
                SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
        }
    }
}
